-- $Id: xpa-net-tcp.adb,v 1.9 2005-12-22 14:58:11 bacon Exp $

with ada.unchecked_deallocation;
with gnat.sockets.constants; use gnat.sockets.constants;
with gnat.sockets.thin; use gnat.sockets.thin;

package body xpa.net.tcp is

	package c renames interfaces.c; 
	use type c.int;

	procedure free is new ada.unchecked_deallocation (tcp_type, tcp_access);

	procedure open (tcp: in out tcp_access; mode: in tcp_mode) is
	begin
		if tcp = null then
			tcp := new tcp_type;
			tcp.dynamic := true;
		end if;

		tcp.mode := mode;

		gnat.sockets.initialize (false);
	exception
		when others => 
			if tcp.dynamic = true then 
				free (tcp);
			end if;
			raise;
	end open;

	procedure close (tcp: in out tcp_access) is
	begin
		if tcp.dynamic = true then
			free (tcp);
		end if;
	end close;

	procedure connect (tcp: in out tcp_access) is
		handle: c.int;
	begin
		handle := c_socket (AF_INET, SOCK_STREAM, 0);
		if handle = -1 then
			raise socket_error;
		end if;

		tcp.handle := handle;
	end connect;

	procedure disconnect (tcp: in out tcp_access) is
	begin
		if c_close(tcp.handle) = -1 then
			raise socket_error;
		end if;
	end disconnect;

	procedure read (tcp: in out tcp_access; 
		data: out byte_array; last: out offset) is
	begin
		if tcp.mode /= binary then
			raise constraint_error;
		end if;

		--receive_socket (tcp.handle,
	end read;

	procedure read (tcp: in out tcp_access;
		data: out str; last: out natural) is 
	begin
		if tcp.mode /= text then
			raise constraint_error;
		end if;
		
	end read;

	procedure write (tcp: in out tcp_access) is
	begin
		null;
	end write;

end xpa.net.tcp;
